package com.supcalls.util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.supcalls.entity.DistributedLock;
import com.supcalls.mapper.DistributedLockMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;

@Component
public class DatabaseLockUtil {

    private final DistributedLockMapper lockMapper;

    public DatabaseLockUtil(DistributedLockMapper lockMapper) {
        this.lockMapper = lockMapper;
    }

    /**
     * 尝试获取锁，并设置超时时间
     * @param lockKey 锁的 key
     * @param timeoutMillis 锁的超时时间（毫秒）
     * @return 是否成功获取锁
     */
    @Transactional
    public boolean tryLockWithTimeout(String lockKey, long timeoutMillis) {
        LocalDateTime timeoutAt = LocalDateTime.now().plus(Duration.ofMillis(timeoutMillis));

        DistributedLock lock = new DistributedLock();
        lock.setLockKey(lockKey);
        lock.setLockedAt(LocalDateTime.now());
        lock.setTimeoutAt(timeoutAt);

        try {
            return lockMapper.insert(lock) > 0;
        } catch (Exception e) {
            return false; // 锁已存在，插入失败
        }
    }

    /**
     * 释放锁，如果锁超时
     * @param lockKey 锁的 key
     */
    @Transactional
    public void releaseLockIfTimeout(String lockKey) {
        DistributedLock lock = lockMapper.selectOne(new QueryWrapper<DistributedLock>().eq("lock_key", lockKey));

        if (lock != null && LocalDateTime.now().isAfter(lock.getTimeoutAt())) {
            // 超过超时时间，释放锁
            lockMapper.delete(new QueryWrapper<DistributedLock>().eq("lock_key", lockKey));
        }
    }
}
